<template>
    <Pop :show="show" :is-close="true" :is-back="false" :is-title="false" @back="onBack" @close="onHide">
        <div class="sub-title">
            <!-- 安全验证 -->
            {{ $t("message.LoginVerify.verify") }}
        </div>
        <v-form validate-on="submit lazy" @submit.prevent="onSubmit">
            <div class="sub-tip_">
                <!-- 邮箱验证码 -->
                {{ $t("message.LoginVerify.captcha") }}
            </div>
            <!-- <v-text-field clearable v-model="code" class="j-input" :rules="codeRules" placeholder="请输入您的邮箱驗證碼"
                :loading="false" color="#15181D" bg-color="#15181D">
                <span class="code-tip had" v-if="hasSend">验证码已发送</span>
                <span class="code-tip" v-else @click="onSend">获取验证码</span>
            </v-text-field> -->
            <div class="ips">
                <JInput v-model="code" :clear="false" :err="loginError"
                    :placeholder="$t('message.LoginVerify.placeholder')"></JInput>
                <div class="code-tip had" v-if="countdown > 0">
                    <!-- 验证码已发送 -->
                    <!-- {{ $t("message.LoginVerify.captchaSend") }} -->
                    {{ countdown }}s
                </div>
                <div class="code-tip" v-else @click="onSend">
                    <!-- 获取验证码 -->
                    {{ $t("message.LoginVerify.getverify") }}
                </div>
            </div>

            <div :class="['sub-tip', !!loginError ? 'mt-top' : '']">
                <!-- 请输入 -->
                {{ $t("message.LoginVerify.input") }}
                {{ account.saveEmail }}
                <!-- 收到的6位验证码 -->
                {{ $t("message.LoginVerify.receivedCode") }}
            </div>

            <div id="cfts"></div>

            <!-- <v-btn class="me-4 submit-btn" color="primary" type="submit"> 提交 </v-btn> -->
            <JButton class="me-4 submit-btn" :label="$t('message.LoginVerify.verify')" @click="onLogin"></JButton>
        </v-form>
    </Pop>
</template>

<script lang="ts" setup>
import { URL_EMAIL_CODE, URL_LOGIN } from "@/comm/api";
import { post } from "@/comm/request";
import Pop from "@/components/pop/index.vue";
import { toast } from "@/components/toast/toast";
import { useAccount } from "@/stores/account";
import { useUser } from "@/stores/user";
import JInput from "@/components/j-input/index.vue";
import JButton from "@/components/j-button/index.vue";
import { Notify } from "@/components/y-notify/script";
import { ref, watch } from "vue";
import i18n from "@/locals";
import { useCountdown } from "./countDown";
import { LoginCall } from "@/comm/Heap";
import { callObj } from "@/comm/loginSucCall";
import { useScale } from "./hooks/scales";
import { onMounted } from "vue";
// const scale = useScale();
let tokens = "";
const account = useAccount();
const user = useUser();
const { countStart, countdown } = useCountdown();
const hasSend = ref(false);
const code = ref("");
const loginError = ref("");


const onBack = () => {
    // account.changePopLogin(true);
    // account.changePopLoginVerify(false);
    hasSend.value = false;
    code.value = "";
    history.back();
};

const props = defineProps({
    show: Boolean
})

const emit = defineEmits(["close"])

watch(()=>props.show, (val)=>{
    if(val){
        changeSize();
    }
})

const changeSize = ()=>{
    let dom: any = document.querySelector(".mask-box");
    if(dom){
        if(window.innerWidth && dom.clientWidth){
            let n = window.innerWidth / dom.clientWidth * 0.92;
            dom.style.transform = `scale(${n})`;
            return true;
        }
    }
    setTimeout(changeSize, 90);
}

onMounted(()=>{
    
})


const onHide = ()=>{
    account.changePopLoginVerify(false);
    emit("close")
}

watch(() => account.popLoginVerify, (v) => {
    if (v) {
        loginError.value = ''
        tokens = "";
    }
    else {
        (window as any).turnstile?.remove();
    }
});


const codeRules = ref([
    (value: string) => {
        if (value) return true;
        return "code is requred.";
    },
    (value: string) => {
        if (value.length === 6) return true;
        return "code must be valid.";
    }
]);

const onLogin = () => {
    // alert("token" + tokens);
    console.log("click login")
    post(
        URL_LOGIN,
        {
            email: localStorage.getItem("email"),
            dynamicCode: code.value,
            // token: tokens
        },
        true
    )
        .then(async (res: any) => {
            // console.log('登录邮箱认证', res);
            // account.changePopLoginVerify(false);
            if (res.code == 200 && res.data) {
                if(res.data.firstLogin){
                    account.changePopRegisterSuccess(true);
                }
                localStorage.setItem("token", res.data.token);
                let err = await user.getUserInfo();
                if (!err) {
                    account.changePopLoginVerify(false);
                    Notify.alert(res.info);
                    callObj.callfun();

                    localStorage.setItem("willJump", "1");
                    location.href = "/";

                } else {
                    Notify.alert(err + "", "warning", 2000);
                    // toast(err + "");
                }
            } else {
                loginError.value = res.info;
                // Notify.alert(res.info + "", "warning", 2000);
                // toast(res.info);
            }
        })
        .catch((err: any) => {
            console.log(err);
            Notify.alert(i18n.global.t("message.LoginVerify.loginFail"), "warning", 2000);
            // toast("登錄失敗");
        });
    hasSend.value = false;
    code.value = "";
};

const onSubmit = async (event: any) => {
    console.log(code.value);
    const res = await event;
    console.log(res);
    if (!res.valid) return;

    onLogin();
};

const onSend = () => {
    hasSend.value = true;
    countStart();
    post(URL_EMAIL_CODE, {
        msgId: 102,
        email: localStorage.getItem("email"),
    })
        .then((res: any) => {
            console.log(res, typeof res);
        })
        .catch((err: any) => {
            console.log(err, "err");
        });
};
</script>

<style lang="less" scoped>
@import url("./index.less");

.v-form {
    min-width: 340px;
    // min-height: 440px;
}

.ips {
    position: relative;
}

.code-tip {
    position: absolute;
    font-size: 12px;
    right: 10px;
    bottom: 0;
    top: 0;
    margin: auto;
    color: var(--main);
    cursor: pointer;
    display: flex;
    align-items: center;
    z-index: 1;
}

.sub-tip_{
    font-size: 16px;
    color: white;
}
.sub-tip {
    font-size: 12px;
    margin-top: 10px;
    color: var(--sub);
    max-width: 360px;
    &.mt-top {
        margin-top: 30px;
    }
}

.had {
    color: var(--sub);
}

.submit-btn {
    margin-top: 48px;
    width: 100%;
    margin-bottom: 20px;
}

.sub-title {
    font-size: 28px;
    margin-bottom: 50px;
    color: #fff;
}

#cfts {
    text-align: center;
    margin-top: 10px;

    iframe {
        width: 90%;
    }
}
</style>
